package com.jarvis.pzz.modules.shop.view;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jarvis.pzz.R;
import com.jarvis.pzz.common.ResponseData;
import com.jarvis.pzz.models.ShopListMapFindModel;
import com.jarvis.pzz.models.ShopsListModel;
import com.jarvis.pzz.modules.shop.adapter.BannerAdapter;
import com.jarvis.pzz.seervers.RequestService;
import com.jarvis.pzz.util.net.RequestApi;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MapFindNewActivity extends Activity {
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();

    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;

    MapView mMapView;
    RecyclerView recycler;
    BaiduMap mBaiduMap;
    private RequestService service;
    private ProgressDialog mDialog;
    private int mark_type = 1; //1一级聚合 2：二级聚合 3：列表
    private boolean isMarkClick = false;
    private LatLng old_center;
    private LatLng before_center;
    private LatLng after_center;
    private List<ShopListMapFindModel> show_data = new ArrayList<>();
    List<Overlay> mOverlayList = new ArrayList<>();
    List<OverlayOptions> overlayOption = new ArrayList<>();
    BannerAdapter adapter;
    LinearLayoutManager layoutManager;
    Marker marker_select;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_marker_cluster_demo);
        mMapView = (MapView) findViewById(R.id.bmapView);
        recycler = (RecyclerView) findViewById(R.id.recycler);
        findViewById(R.id.rel_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        service = RequestApi.create(RequestService.class);
        mBaiduMap = mMapView.getMap();

//        LatLng position = new LatLng(39.914935, 116.403119);
//        MapStatus.Builder builder = new MapStatus.Builder();
//        builder.target(position).zoom(16.0f);
//        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));


        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
        adapter = new BannerAdapter(R.layout.item_shop, show_data);
        //adapter = new BannerAdapter(this, show_data);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recycler.setLayoutManager(layoutManager);
        recycler.setHasFixedSize(true);
        recycler.setAdapter(adapter);
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(recycler);
        recycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                ShopListMapFindModel shopListModel = adapter.getData().get(i);
                String shopId = shopListModel.getShopId();
                startActivity(new Intent(MapFindNewActivity.this, ShopDetailsActivity.class).putExtra("shopId", shopId));
            }
        });
        recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int i = layoutManager.findFirstVisibleItemPosition();
                    //Toast.makeText(getApplicationContext(), i + "", Toast.LENGTH_SHORT).show();
                    //得到指示器红点的位置
                    addOnMake(chageToLanlng(show_data.get(i).getLatitude(), show_data.get(i).getLongitude()));
                    System.out.println("--------3:" + i + ":" + chageToLanlng(show_data.get(i).getLatitude(), show_data.get(i).getLongitude()));
                }
            }
        });
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

                    if(marker_select!=null){
                        if(marker.getPosition()==marker_select.getPosition()){
                            return true;
                        }
                    }

                    recycler.setVisibility(View.GONE);
                    if (mark_type == 1) {
                        isMarkClick = true;
                        LatLng position = marker.getPosition();
                        MapStatus.Builder builder = new MapStatus.Builder();
                        builder.target(position).zoom(16.0f);
                        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                        old_center = position;
                        mark_type = 3;
                        loadList();
                    }
//                else if (mark_type == 2) {
//                    isMarkClick = true;
//                    LatLng position = marker.getPosition();
//                    MapStatus.Builder builder = new MapStatus.Builder();
//                    builder.target(position).zoom(16.0f);
//                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
//                    old_center = position;
//                    mark_type = 3;
//                    loadList();
//                }
                    else if (mark_type == 3) {
                        recycler.setVisibility(View.VISIBLE);
                        int index = marker.getExtraInfo().getInt("index");
                        //Toast.makeText(getApplicationContext(), index + "", Toast.LENGTH_SHORT).show();

                        recycler.scrollToPosition(index);
                        addOnMake(chageToLanlng(show_data.get(index).getLatitude(), show_data.get(index).getLongitude()));
                        System.out.println("--------1:" + index + ":" + chageToLanlng(show_data.get(index).getLatitude(), show_data.get(index).getLongitude()));
                        System.out.println("--------2:" + index + ":" + marker.getPosition());
                    }
                return true;
            }
        });
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
                before_center = mapStatus.target;
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                recycler.setVisibility(View.GONE);
                if (marker_select != null) {
                    marker_select.remove();
                    marker_select = null;
                }
                after_center = mapStatus.target;
                double distance_one = DistanceUtil.getDistance(before_center, after_center);
                double distance_total = DistanceUtil.getDistance(old_center, after_center);
                System.out.println("distance_total:" + distance_total);
                if (isMarkClick) {
                    isMarkClick = false;
                    return;
                }
                if (mapStatus.zoom < 16 && distance_one < 1 && mark_type != 1) {
                    //Toast.makeText(getApplicationContext(), "地图缩放，加载一聚合", Toast.LENGTH_SHORT).show();
                    mark_type = 1;
                    loadList();
                    return;
                }
//                if (mapStatus.zoom < 16 && mapStatus.zoom > 14 && distance_one < 1 && mark_type != 2) {
//                    Toast.makeText(getApplicationContext(), "地图缩放，加载二级聚合", Toast.LENGTH_SHORT).show();
//                    mark_type = 2;
//                    loadList();
//                    return;
//                }
                if (mapStatus.zoom >= 16 && distance_one < 1 && mark_type != 3) {
                    mark_type = 3;
                    //Toast.makeText(getApplicationContext(), "地图缩放，加载列表", Toast.LENGTH_SHORT).show();
                    loadList();
                    return;
                }
                if (mark_type == 1 && distance_total > 15000) {
                    // Toast.makeText(getApplicationContext(), "移动满15公里，加载一级聚合", Toast.LENGTH_SHORT).show();
                    old_center = after_center;
                    loadList();
                    return;
                }
//                if (mark_type == 2 && distance_total > 8000) {
//                    Toast.makeText(getApplicationContext(), "移动满8公里，加载二级聚合", Toast.LENGTH_SHORT).show();
//                    old_center = after_center;
//                    loadList();
//                    return;
//                }
                if (mark_type == 3 && distance_total > 3000) {
                    // Toast.makeText(getApplicationContext(), "移动满3公里，加载列表", Toast.LENGTH_SHORT).show();
                    old_center = after_center;
                    loadList();
                    return;
                }
//
            }
        });

    }

    private void addOnMake(LatLng position) {
        if (marker_select != null) {
            marker_select.remove();
            marker_select = null;
        }
//构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.icon_marka);

//构建MarkerOption，用于在地图上添加Marker

        OverlayOptions option = new MarkerOptions()
                .position(position)
                .icon(bitmap);

        marker_select = (Marker) (mBaiduMap.addOverlay(option));
    }

    private void loadList() {
        if (mDialog == null)
            mDialog = new ProgressDialog(this);
        mDialog.setCancelable(false);
        mDialog.setMessage("loading");
        mDialog.show();
        Call<ResponseData<ShopsListModel>> shopsListWithLocation = service.getShopsListWithLocationFilter(mark_type, old_center.latitude + "", old_center.longitude + "");
        shopsListWithLocation.enqueue(new Callback<ResponseData<ShopsListModel>>() {
            @Override
            public void onResponse(Call<ResponseData<ShopsListModel>> call, Response<ResponseData<ShopsListModel>> response) {
                mDialog.dismiss();
                if (response.body() != null) {
                    int resultCode = response.body().getResultCode();
                    if (resultCode == 200) {
                        ShopsListModel data = response.body().getData();
                        if (mark_type == 3) {
                            addSmallMarkers(data);
                        } else {
                            addMarkers(data);
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "请求失败", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(Call<ResponseData<ShopsListModel>> call, Throwable t) {
                mDialog.dismiss();
                Toast.makeText(getApplicationContext(), RequestApi.detailError(t), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void addMarkers(ShopsListModel data) {
        mBaiduMap.clear();
        LatLng point = null;
        BitmapDescriptor bitmap;
        OverlayOptions option;
        View view = LayoutInflater.from(MapFindNewActivity.this).inflate(R.layout.total_map, null);
        TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
        TextView tv_value = (TextView) view.findViewById(R.id.tv_value);
        List<ShopListMapFindModel> shopsList = data.getShopsList();
        for (int i = 0; i < shopsList.size(); i++) {

            ShopListMapFindModel shopListMapFindModel = shopsList.get(i);
            tv_name.setText(shopListMapFindModel.getName());
            tv_value.setText(shopListMapFindModel.getCount());
            if (TextUtils.isEmpty(shopListMapFindModel.getLatitude()) || TextUtils.isEmpty(shopListMapFindModel.getLongitude())) {

            } else {
                point = chageToLanlng(shopListMapFindModel.getLatitude(), shopListMapFindModel.getLongitude());
//构建Marker图标
                bitmap = BitmapDescriptorFactory
                        .fromView(view);
//构建MarkerOption，用于在地图上添加Marker

                option = new MarkerOptions()
                        .position(point)
                        .icon(bitmap);

//在地图上添加Marker，并显示

                mBaiduMap.addOverlay(option);
            }

        }
    }

    private void addSmallMarkers(ShopsListModel data) {
        mBaiduMap.clear();
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.img_small_location);
        List<ShopListMapFindModel> shopsList = data.getShopsList();
        overlayOption = getOverlayOptions(shopsList, bitmap);
        addToMap();

    }

    /**
     * 将所有Overlay 添加到地图上
     */
    public void addToMap() {
        if (mBaiduMap == null) {
            return;
        }
        for (OverlayOptions option : overlayOption) {
            mOverlayList.add(mBaiduMap.addOverlay(option));
        }
    }

    public final List<OverlayOptions> getOverlayOptions(List<ShopListMapFindModel> shopsList, BitmapDescriptor centerBitmap) {
        if (shopsList == null) {
            return null;
        }
        show_data.clear();
        List<OverlayOptions> markerList = new ArrayList<OverlayOptions>();
        for (int i = 0; i < shopsList.size(); i++) {
            ShopListMapFindModel shopListMapFindModel = shopsList.get(i);
            if (TextUtils.isEmpty(shopListMapFindModel.getLatitude()) || TextUtils.isEmpty(shopListMapFindModel.getLongitude())) {
                System.out.println("--------:" + i);
            } else {
                show_data.add(shopListMapFindModel);
                if (i == 12) {
                    System.out.println("--------0:" + i + ":" + chageToLanlng(shopListMapFindModel.getLatitude(), shopListMapFindModel.getLongitude()));
                }
                Bundle bundle = new Bundle();
                bundle.putInt("index", i);
                markerList.add(new MarkerOptions()
                        .icon(centerBitmap).extraInfo(bundle)
                        .position(chageToLanlng(shopListMapFindModel.getLatitude(), shopListMapFindModel.getLongitude())));
            }
        }
        adapter.notifyDataSetChanged();
        return markerList;
    }

    private LatLng chageToLanlng(String s, String v) {
        return new LatLng(Float.valueOf(s), Float.valueOf(v));
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        super.onDestroy();
    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                old_center = ll;
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                loadList();
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }
}
